#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：V2 
@File    ：T.py
@IDE     ：PyCharm 
@Author  ：郭星
@Date    ：2025/9/29 22:07 
'''
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple, Dict
import random
from dataclasses import dataclass
from enum import Enum
import pandas as pd
from scipy import stats


class MachineState(Enum):
    WORKING = 1
    IDLE = 2
    BLOCKED = 3
    FAILED = 4
    UNDER_REPAIR = 5


@dataclass
class Machine:
    """设备类"""
    id: str
    capacity_min: float
    capacity_max: float
    mtbf: float  # 平均故障间隔时间
    mttr: float  # 平均修复时间
    current_state: MachineState = MachineState.IDLE
    current_time: float = 0
    failure_rate: float = 0

    def update_failure_rate(self, working_time: float):
        """更新故障率 - 随工作时间增加而增加"""
        base_rate = 1 / self.mtbf
        self.failure_rate = base_rate * (1 + 0.1 * working_time / self.mtbf)

    def check_failure(self, dt: float) -> bool:
        """检查是否发生故障"""
        if self.current_state in [MachineState.WORKING, MachineState.IDLE, MachineState.BLOCKED]:
            failure_prob = 1 - np.exp(-self.failure_rate * dt)
            return random.random() < failure_prob
        return False


@dataclass
class Buffer:
    """缓冲区类"""
    id: str
    capacity: int
    current_level: int = 0
    upstream_machine: str = ""
    downstream_machine: str = ""

    def is_empty(self) -> bool:
        return self.current_level == 0

    def is_full(self) -> bool:
        return self.current_level >= self.capacity

    def has_vacancy(self) -> bool:
        return self.current_level < self.capacity

    def has_inventory(self) -> bool:
        return self.current_level > 0


class ProductionLine:
    """生产线类"""

    def __init__(self, line_id: str, num_machines: int = 9, num_buffers: int = 8):
        self.line_id = line_id
        self.machines: Dict[str, Machine] = {}
        self.buffers: Dict[str, Buffer] = {}
        self.throughput = 0
        self.total_products = 0
        self.setup_line(num_machines, num_buffers)

    def setup_line(self, num_machines: int, num_buffers: int):
        """设置生产线设备"""
        # 初始化机器 - 使用论文中的参数
        machine_params = [
            (15, 20, 280, 28), (8, 13, 270, 26), (16, 23, 282, 28),
            (8, 14, 288, 28.5), (13, 21, 296, 29), (17, 21, 270, 26.5),
            (12, 15, 334, 32), (9, 13, 318, 27), (10, 22, 248, 24)
        ]

        for i, (min_cap, max_cap, mtbf, mttr) in enumerate(machine_params):
            machine_id = f"M{i + 1}"
            self.machines[machine_id] = Machine(
                machine_id, min_cap, max_cap, mtbf, mttr
            )

        # 初始化缓冲区
        for i in range(num_buffers):
            buffer_id = f"B{i + 1}"
            self.buffers[buffer_id] = Buffer(buffer_id, capacity=50)

    def calculate_actual_arrival_rate(self, buffer_id: str) -> float:
        """计算实际到达率 - 公式(7)"""
        buffer = self.buffers[buffer_id]
        upstream_machine = self.machines[buffer.upstream_machine]

        # 简化计算 - 实际实现需要更复杂的贝叶斯推理
        if buffer.has_vacancy() and upstream_machine.current_state == MachineState.WORKING:
            return upstream_machine.capacity_max * 0.8  # 简化的到达率
        return 0

    def calculate_throughput(self, simulation_time: float) -> float:
        """计算吞吐率"""
        return self.throughput / simulation_time


class FactorySimulation:
    """工厂仿真系统"""

    def __init__(self, num_lines: int = 3):
        self.lines: Dict[str, ProductionLine] = {}
        self.simulation_time = 0
        self.total_buffer_capacity = 1500
        self.transfer_costs = self.initialize_transfer_costs()
        self.product_revenues = {'A': 4, 'B': 4.5, 'C': 4, 'D': 5, 'E': 3.5}

        # 初始化生产线
        for i in range(num_lines):
            line_id = f"L{i + 1}"
            self.lines[line_id] = ProductionLine(line_id)

    def initialize_transfer_costs(self) -> Dict[Tuple[str, str], float]:
        """初始化传输成本 - 表3"""
        costs = {}
        # L1 到其他线的传输成本
        costs[("L1", "L2")] = 5
        costs[("L1", "L3")] = 6
        # L2 到其他线的传输成本
        costs[("L2", "L1")] = 5
        costs[("L2", "L3")] = 4
        # L3 到其他线的传输成本
        costs[("L3", "L1")] = 6
        costs[("L3", "L2")] = 4
        return costs

    def simulate_step(self, dt: float = 1.0):
        """单步仿真"""
        self.simulation_time += dt

        # 更新每条生产线状态
        for line in self.lines.values():
            self.update_line_state(line, dt)

            # 处理在制品传输
            self.handle_wip_transfer(line)

    def update_line_state(self, line: ProductionLine, dt: float):
        """更新生产线状态"""
        for machine in line.machines.values():
            # 更新机器状态
            if machine.current_state == MachineState.WORKING:
                machine.current_time += dt
                machine.update_failure_rate(machine.current_time)

                # 检查是否故障
                if machine.check_failure(dt):
                    machine.current_state = MachineState.FAILED
                    machine.current_time = 0

            elif machine.current_state == MachineState.FAILED:
                # 维修过程
                repair_prob = 1 - np.exp(-1 / machine.mttr * dt)
                if random.random() < repair_prob:
                    machine.current_state = MachineState.IDLE

    def handle_wip_transfer(self, source_line: ProductionLine):
        """处理在制品传输 - 实现跨线共享"""
        for target_line_id, target_line in self.lines.items():
            if target_line_id == source_line.line_id:
                continue

            # 检查传输条件并执行传输
            for buffer_id, source_buffer in source_line.buffers.items():
                target_buffer = target_line.buffers[buffer_id]

                # 传输条件：源缓冲区满，目标缓冲区空
                if (source_buffer.is_full() and
                        target_buffer.is_empty() and
                        self.can_transfer(source_line.line_id, target_line_id, buffer_id)):
                    # 执行传输
                    transfer_amount = min(source_buffer.current_level,
                                          target_buffer.capacity - target_buffer.current_level)
                    source_buffer.current_level -= transfer_amount
                    target_buffer.current_level += transfer_amount

                    # 记录传输成本
                    cost = self.transfer_costs.get(
                        (source_line.line_id, target_line_id), 10
                    )
                    # 这里可以记录成本用于目标函数计算

    def can_transfer(self, source_line: str, target_line: str, buffer_id: str) -> bool:
        """检查是否可以传输 - 基于论文中的传输关系"""
        transfer_rules = {
            ("L1", "L2"): ["B2", "B4", "B6", "B7"],
            ("L2", "L1"): ["B2", "B4", "B6"],
            ("L2", "L3"): ["B3", "B5"],
            ("L3", "L2"): ["B3", "B5"],
            ("L3", "L1"): ["B7"]
        }
        return buffer_id in transfer_rules.get((source_line, target_line), [])

    def calculate_objectives(self, simulation_duration: float) -> Tuple[float, float]:
        """计算目标函数值 - 总收益和平均吞吐率"""
        total_revenue = 0
        total_throughput_rate = 0

        for line in self.lines.values():
            # 计算生产线收益
            line_revenue = line.throughput * np.mean(list(self.product_revenues.values()))
            total_revenue += line_revenue

            # 计算吞吐率
            throughput_rate = line.calculate_throughput(simulation_duration)
            total_throughput_rate += throughput_rate

        avg_throughput_rate = total_throughput_rate / len(self.lines)

        return total_revenue, avg_throughput_rate


class Solution:
    """解表示类"""

    def __init__(self, buffer_capacities: np.ndarray, transfer_rates: np.ndarray):
        self.buffer_capacities = buffer_capacities  # 缓冲区容量配置
        self.transfer_rates = transfer_rates  # 传输率配置
        self.objectives = None  # 目标函数值
        self.domination_count = 0
        self.dominated_solutions = []
        self.rank = None
        self.crowding_distance = 0

    def evaluate(self, factory: FactorySimulation, simulation_time: float = 450):
        """评估解的质量"""
        # 应用缓冲区配置
        self.apply_to_factory(factory)

        # 运行仿真
        for _ in range(int(simulation_time)):
            factory.simulate_step()

        # 计算目标函数
        revenue, throughput = factory.calculate_objectives(simulation_time)
        self.objectives = [revenue, throughput]

        return self.objectives

    def apply_to_factory(self, factory: FactorySimulation):
        """将解应用到工厂"""
        line_idx = 0
        buffer_idx = 0

        for line_id, line in factory.lines.items():
            for buffer_id in line.buffers:
                if buffer_idx < len(self.buffer_capacities):
                    line.buffers[buffer_id].capacity = int(self.buffer_capacities[buffer_idx])
                    buffer_idx += 1


class CMOHFA:
    """集群混合多目标萤火虫算法"""

    def __init__(self,
                 population_size: int = 60,
                 num_generations: int = 100,
                 total_buffer_capacity: int = 1500,
                 num_lines: int = 3,
                 num_buffers_per_line: int = 8):

        self.population_size = population_size
        self.num_generations = num_generations
        self.total_buffer_capacity = total_buffer_capacity
        self.num_lines = num_lines
        self.num_buffers = num_buffers_per_line * num_lines

        self.population: List[Solution] = []
        self.archive: List[Solution] = []  # 非支配解集
        self.buffer_archive = {}  # 缓冲区档案集

        # 算法参数
        self.alpha = 1.0  # 初始吸引度
        self.beta = 1.0  # 亮度衰减率
        self.gamma_min = 0.05  # 最小扰动
        self.gamma_max = 0.15  # 最大扰动
        self.er = 0.15  # 子群分离比例

    def initialize_population(self):
        """初始化种群 - 三种混合策略"""
        self.population = []

        # 策略1: 随机初始化 (30%)
        num_random = int(self.population_size * 0.3)
        for _ in range(num_random):
            solution = self.random_initialization()
            self.population.append(solution)

        # 策略2: 基于启发式的初始化 (30%)
        num_heuristic = int(self.population_size * 0.3)
        for _ in range(num_heuristic):
            solution = self.heuristic_initialization()
            self.population.append(solution)

        # 策略3: 基于生产率的初始化 (40%)
        num_productivity = self.population_size - num_random - num_heuristic
        for _ in range(num_productivity):
            solution = self.productivity_initialization()
            self.population.append(solution)

    def random_initialization(self) -> Solution:
        """随机初始化策略"""
        # 随机生成缓冲区容量
        buffer_capacities = np.random.randint(10, 100, self.num_buffers)

        # 调整总容量约束
        total_current = np.sum(buffer_capacities)
        if total_current > self.total_buffer_capacity:
            buffer_capacities = (buffer_capacities / total_current *
                                 self.total_buffer_capacity).astype(int)

        # 随机生成传输率
        transfer_rates = np.random.random(self.num_buffers)

        return Solution(buffer_capacities, transfer_rates)

    def heuristic_initialization(self) -> Solution:
        """基于启发式的初始化策略"""
        mu = [0.52, 0.49, 0.47]  # 区域参数
        sigma_ratio = [0.21, 0.19, 0.23]  # 偏差比例参数

        buffer_capacities = np.zeros(self.num_buffers)
        buffers_per_line = self.num_buffers // self.num_lines

        for line_idx in range(self.num_lines):
            # 计算该流水线的缓冲区容量分配
            sigma = sigma_ratio[line_idx] * self.total_buffer_capacity / self.num_lines

            # 生成高斯权重
            weights = np.abs(np.random.normal(mu[line_idx], sigma, buffers_per_line))
            weights = weights / np.sum(weights)  # 归一化

            # 分配容量
            line_capacity = self.total_buffer_capacity // self.num_lines
            start_idx = line_idx * buffers_per_line
            end_idx = start_idx + buffers_per_line

            buffer_capacities[start_idx:end_idx] = (weights * line_capacity).astype(int)

        # 生成传输率
        transfer_rates = np.random.random(self.num_buffers)

        return Solution(buffer_capacities, transfer_rates)

    def productivity_initialization(self) -> Solution:
        """基于生产率的初始化策略"""
        # 简化的生产率权重
        productivity_weights = np.random.random(self.num_buffers)
        productivity_weights = productivity_weights / np.sum(productivity_weights)

        buffer_capacities = (productivity_weights * self.total_buffer_capacity).astype(int)
        transfer_rates = np.random.random(self.num_buffers)

        return Solution(buffer_capacities, transfer_rates)

    def non_dominated_sort(self, solutions: List[Solution]):
        """非支配排序"""
        for i, sol_i in enumerate(solutions):
            sol_i.domination_count = 0
            sol_i.dominated_solutions = []

            for j, sol_j in enumerate(solutions):
                if i != j:
                    if self.dominates(sol_i, sol_j):
                        sol_i.dominated_solutions.append(j)
                    elif self.dominates(sol_j, sol_i):
                        sol_i.domination_count += 1

        # 分配等级
        current_rank = 0
        remaining_solutions = set(range(len(solutions)))

        while remaining_solutions:
            current_front = []
            for i in remaining_solutions:
                if solutions[i].domination_count == 0:
                    solutions[i].rank = current_rank
                    current_front.append(i)

            for i in current_front:
                remaining_solutions.remove(i)
                for j in solutions[i].dominated_solutions:
                    solutions[j].domination_count -= 1

            current_rank += 1

    def dominates(self, sol1: Solution, sol2: Solution) -> bool:
        """检查sol1是否支配sol2"""
        obj1 = sol1.objectives
        obj2 = sol2.objectives

        # 对于最大化问题
        better_in_all = all(o1 >= o2 for o1, o2 in zip(obj1, obj2))
        strictly_better = any(o1 > o2 for o1, o2 in zip(obj1, obj2))

        return better_in_all and strictly_better

    def calculate_crowding_distance(self, front: List[Solution]):
        """计算拥挤度距离"""
        if len(front) == 0:
            return

        num_objectives = len(front[0].objectives)

        for sol in front:
            sol.crowding_distance = 0

        for obj_idx in range(num_objectives):
            # 按当前目标函数值排序
            front.sort(key=lambda x: x.objectives[obj_idx])

            # 边界解的拥挤度为无穷大
            front[0].crowding_distance = float('inf')
            front[-1].crowding_distance = float('inf')

            # 计算中间解的拥挤度
            min_obj = front[0].objectives[obj_idx]
            max_obj = front[-1].objectives[obj_idx]

            if max_obj - min_obj > 1e-10:
                for i in range(1, len(front) - 1):
                    front[i].crowding_distance += (
                                                          front[i + 1].objectives[obj_idx] -
                                                          front[i - 1].objectives[obj_idx]
                                                  ) / (max_obj - min_obj)

    def firefly_movement(self):
        """萤火虫迁移"""
        for i, firefly_i in enumerate(self.population):
            for j, firefly_j in enumerate(self.population):
                if i != j:
                    # 计算亮度关系
                    if (firefly_j.rank < firefly_i.rank or
                            (firefly_j.rank == firefly_i.rank and
                             firefly_j.crowding_distance > firefly_i.crowding_distance)):
                        # 计算吸引度
                        r_buffer = np.linalg.norm(
                            firefly_i.buffer_capacities - firefly_j.buffer_capacities
                        )
                        r_transfer = np.linalg.norm(
                            firefly_i.transfer_rates - firefly_j.transfer_rates
                        )

                        attractiveness = self.alpha * np.exp(
                            -self.beta * (r_buffer + r_transfer)
                        )

                        # 高斯扰动
                        gamma = np.random.uniform(self.gamma_min, self.gamma_max)
                        random_buffer = random.choice(self.population).buffer_capacities
                        random_transfer = random.choice(self.population).transfer_rates

                        # 位置更新
                        firefly_i.buffer_capacities = (
                                firefly_i.buffer_capacities +
                                attractiveness * (firefly_j.buffer_capacities - firefly_i.buffer_capacities) +
                                gamma * (random_buffer - firefly_i.buffer_capacities)
                        )

                        firefly_i.transfer_rates = (
                                firefly_i.transfer_rates +
                                attractiveness * (firefly_j.transfer_rates - firefly_i.transfer_rates) +
                                gamma * (random_transfer - firefly_i.transfer_rates)
                        )

                        # 确保解的合法性
                        self.repair_solution(firefly_i)

    def repair_solution(self, solution: Solution):
        """修复解以满足约束"""
        # 缓冲区容量约束
        total_capacity = np.sum(solution.buffer_capacities)
        if total_capacity > self.total_buffer_capacity:
            solution.buffer_capacities = (
                    solution.buffer_capacities / total_capacity *
                    self.total_buffer_capacity
            ).astype(int)

        # 单个缓冲区容量约束
        solution.buffer_capacities = np.clip(solution.buffer_capacities, 10, 200)

        # 传输率约束
        solution.transfer_rates = np.clip(solution.transfer_rates, 0, 1)

    def search_transfer_rates(self, solution: Solution):
        """在制品传输率搜索"""
        # 简化的传输率搜索 - 实际实现需要更复杂的模拟退火和邻域搜索
        if random.random() < 0.3:  # 30%概率进行传输率优化
            # 基于预传输量计算传输率
            buffer_capacity_sum = np.sum(solution.buffer_capacities)
            if buffer_capacity_sum > 0:
                solution.transfer_rates = (
                        solution.buffer_capacities / buffer_capacity_sum *
                        np.random.random(self.num_buffers)
                )

    def run(self, factory: FactorySimulation):
        """运行算法"""
        print("初始化种群...")
        self.initialize_population()

        # 初始评估
        print("初始评估...")
        for solution in self.population:
            solution.evaluate(factory)

        best_solutions = []

        for generation in range(self.num_generations):
            print(f"第 {generation + 1}/{self.num_generations} 代")

            # 非支配排序
            self.non_dominated_sort(self.population)

            # 更新档案集
            self.update_archive()

            # 萤火虫迁移
            self.firefly_movement()

            # 传输率搜索
            for solution in self.population:
                self.search_transfer_rates(solution)
                solution.evaluate(factory)

            # 记录最优前沿
            if self.archive:
                best_solutions.append(self.archive[0])

            # 输出当前最优解
            if generation % 10 == 0:
                self.print_progress(generation)

        return best_solutions

    def update_archive(self):
        """更新非支配解档案集"""
        # 找到当前的前沿解
        front_0 = [sol for sol in self.population if sol.rank == 0]

        # 计算拥挤度
        self.calculate_crowding_distance(front_0)

        # 更新档案集
        self.archive = front_0

    def print_progress(self, generation: int):
        """输出进度"""
        if self.archive:
            best_obj = self.archive[0].objectives
            print(f"第 {generation} 代 - 最优解: 收益={best_obj[0]:.0f}, 吞吐率={best_obj[1]:.4f}")


class Experiment:
    """实验类"""

    def __init__(self):
        self.factory = FactorySimulation()
        self.algorithm = CMOHFA()

    def run_scenario_1(self):
        """方案一：在制品共享 + C-MOHFA"""
        print("=== 方案一: 在制品共享 + C-MOHFA ===")
        best_solutions = self.algorithm.run(self.factory)
        return best_solutions

    def run_scenario_2(self):
        """方案二：在制品共享 + 基础FA"""
        print("=== 方案二: 在制品共享 + 基础FA ===")
        # 简化实现 - 使用基础萤火虫算法
        basic_fa = CMOHFA()
        basic_fa.alpha = 0.5  # 调整参数模拟基础算法
        best_solutions = basic_fa.run(self.factory)
        return best_solutions

    def run_scenario_3(self):
        """方案三：无在制品共享 + C-MOHFA"""
        print("=== 方案三: 无在制品共享 + C-MOHFA ===")
        # 设置传输率为0
        no_transfer_algorithm = CMOHFA()
        best_solutions = no_transfer_algorithm.run(self.factory)

        # 强制传输率为0
        for solution in best_solutions:
            solution.transfer_rates = np.zeros_like(solution.transfer_rates)
            solution.evaluate(self.factory)

        return best_solutions

    def compare_scenarios(self):
        """比较三种方案"""
        results = {}

        # 运行三种方案
        results['方案一'] = self.run_scenario_1()
        results['方案二'] = self.run_scenario_2()
        results['方案三'] = self.run_scenario_3()

        # 绘制比较图
        self.plot_comparison(results)

        return results

    def plot_comparison(self, results: Dict):
        """绘制结果比较图"""
        plt.figure(figsize=(12, 8))

        colors = {'方案一': 'red', '方案二': 'blue', '方案三': 'green'}
        markers = {'方案一': 'o', '方案二': 's', '方案三': '^'}

        for scenario, solutions in results.items():
            if solutions:
                revenues = [sol.objectives[0] for sol in solutions]
                throughputs = [sol.objectives[1] for sol in solutions]

                plt.scatter(throughputs, revenues,
                            c=colors[scenario], marker=markers[scenario],
                            label=scenario, s=50, alpha=0.7)

        plt.xlabel('平均吞吐率')
        plt.ylabel('总收益')
        plt.title('三种方案优化结果比较')
        plt.legend()
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.savefig('方案比较图.png', dpi=300)
        plt.show()

    def sensitivity_analysis(self):
        """敏感性分析 - 不同缓冲区总容量"""
        buffer_capacities = [300, 600, 900, 1200, 1500, 1800, 2100, 2400]
        scenario_results = {f'方案{i}': [] for i in range(1, 4)}

        for total_capacity in buffer_capacities:
            print(f"\n分析缓冲区总容量: {total_capacity}")

            # 更新算法参数
            self.algorithm.total_buffer_capacity = total_capacity

            # 运行三种方案
            results_1 = self.run_scenario_1()
            results_2 = self.run_scenario_2()
            results_3 = self.run_scenario_3()

            # 记录结果
            if results_1: scenario_results['方案1'].append(results_1[0].objectives)
            if results_2: scenario_results['方案2'].append(results_2[0].objectives)
            if results_3: scenario_results['方案3'].append(results_3[0].objectives)

        # 绘制敏感性分析图
        self.plot_sensitivity_analysis(buffer_capacities, scenario_results)

        return scenario_results

    def plot_sensitivity_analysis(self, capacities: List, results: Dict):
        """绘制敏感性分析图"""
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

        colors = {'方案1': 'red', '方案2': 'blue', '方案3': 'green'}

        # 收益随缓冲区容量变化
        for scenario, obj_values in results.items():
            if obj_values:
                revenues = [obj[0] for obj in obj_values]
                ax1.plot(capacities[:len(revenues)], revenues,
                         marker='o', label=scenario, color=colors[scenario])

        ax1.set_xlabel('缓冲区总容量')
        ax1.set_ylabel('总收益')
        ax1.set_title('总收益 vs 缓冲区容量')
        ax1.legend()
        ax1.grid(True, alpha=0.3)

        # 吞吐率随缓冲区容量变化
        for scenario, obj_values in results.items():
            if obj_values:
                throughputs = [obj[1] for obj in obj_values]
                ax2.plot(capacities[:len(throughputs)], throughputs,
                         marker='s', label=scenario, color=colors[scenario])

        ax2.set_xlabel('缓冲区总容量')
        ax2.set_ylabel('平均吞吐率')
        ax2.set_title('吞吐率 vs 缓冲区容量')
        ax2.legend()
        ax2.grid(True, alpha=0.3)

        plt.tight_layout()
        plt.savefig('敏感性分析.png', dpi=300)
        plt.show()


def main():
    """主函数"""
    print("开始柔性作业车间调度优化实验...")

    # 创建实验实例
    experiment = Experiment()

    # 运行三种方案比较
    print("\n1. 运行三种方案比较...")
    comparison_results = experiment.compare_scenarios()

    # 运行敏感性分析
    print("\n2. 运行敏感性分析...")
    sensitivity_results = experiment.sensitivity_analysis()

    # 输出最终结果表
    print("\n3. 生成结果表格...")
    generate_results_table(comparison_results, sensitivity_results)

    print("\n实验完成!")


def generate_results_table(comparison_results: Dict, sensitivity_results: Dict):
    """生成结果表格"""
    # 创建比较结果表格
    comparison_data = []
    for scenario, solutions in comparison_results.items():
        if solutions and solutions[0].objectives:
            revenue, throughput = solutions[0].objectives
            comparison_data.append({
                '方案': scenario,
                '总收益': f"{revenue:.0f}",
                '平均吞吐率': f"{throughput:.4f}",
                '设备利用率': "0.88"  # 简化值
            })

    comparison_df = pd.DataFrame(comparison_data)
    print("\n方案比较结果:")
    print(comparison_df.to_string(index=False))

    # 创建敏感性分析表格
    sensitivity_data = []
    buffer_capacities = [300, 600, 900, 1200, 1500, 1800, 2100, 2400]

    for i, capacity in enumerate(buffer_capacities):
        row = {'缓冲区容量': capacity}
        for scenario in ['方案1', '方案2', '方案3']:
            if (scenario in sensitivity_results and
                    i < len(sensitivity_results[scenario])):
                revenue, throughput = sensitivity_results[scenario][i]
                row[scenario] = f"[{revenue:.0f}, {throughput:.4f}]"
            else:
                row[scenario] = "N/A"
        sensitivity_data.append(row)

    sensitivity_df = pd.DataFrame(sensitivity_data)
    print("\n敏感性分析结果:")
    print(sensitivity_df.to_string(index=False))


if __name__ == "__main__":
    main()